import React from 'react';
import { Form, Input, Modal, message, Table } from 'antd';
import Api from 'Utils/api';
import './index.scss';

const FormItem = Form.Item;
const AddForm = Form.create()(
  (props) => {
    const { form, initialValue } = props;
    const { getFieldDecorator } = form;

    return (
      <Form>
        <FormItem
          label="角色名称:"
        >
          {
            getFieldDecorator('name', {
              initialValue: initialValue ? initialValue.name : '',
            })(
              <Input placeholder="请输入角色名称" style={{ width: 500 }} />
            )
          }
        </FormItem>
        <FormItem
          label="描述:"
        >
          {
            getFieldDecorator('description', {
              initialValue: initialValue ? initialValue.description : '',
            })(
              <Input placeholder="请输入描述" style={{ width: 500 }} />
            )
          }
        </FormItem>
      </Form>
    );
  }
);
const PAGE_SIZE = 5;
class AddModal extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      loading: false,
      isAdd: false,
      record: '',
      dataCount: 0,
      data: [],
      listPage: 1,
      selectedRowKeys: undefined,
    };
    this.condition = { offset: 0, limit: PAGE_SIZE };
    this.initList = ::this.initList;
    this.initRowSelection = ::this.initRowSelection;
  }
  componentDidMount() {
    this.initList();
  }
  initList() {
    const api = new Api({
      method: 'GET',
      path: '/permissions',
      query: { ...this.condition },
      success: (json) => {
        this.setState({ listPage: ((this.condition.offset / PAGE_SIZE) + 1), data: json.data_list, dataCount: json.total_count });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  onListPageChange(page) {
    this.setState({ listPage: page }, this.initList.bind(this));
    this.condition.offset = (page - 1) * PAGE_SIZE;
  }
  generatorColumns() {
    return [
      {
        title: '权限名',
        dataIndex: 'name',
        render: text => (
          <span>{text}</span>
        )
      },
      {
        title: '描述',
        dataIndex: 'description',
        render: text => (
          <span >{text}</span >
        )
      },
    ];
  }
  showModal(record) {
    const self = this;
    this.setState({
      visible: true,
      record: record,
    }, () => {
      self.form.resetFields();
      this.initRowSelection();
    });
    if (!record.id) {
      this.setState({ isAdd: true });
    } else {
      this.setState({ isAdd: false });
    }
  }
  close() {
    this.setState({
      loading: false,
      visible: false,
    });
  }
  initRowSelection() {
    const newSelectedRowKeys = [];
    if (this.state.record.id) {
      for (let i = 0; i < this.state.record.permissions.length; i++) {
        newSelectedRowKeys.push(this.state.record.permissions[i].id);
      }
      this.setState({
        selectedRowKeys: newSelectedRowKeys,
      });
    } else {
      this.setState({
        selectedRowKeys: undefined,
      });
    }
  }
  validation(value) {
    if (!value.name || !value.description || !this.state.selectedRowKeys) {
      return false;
    }
    return true;
  }

  handleOk() {
    const { isAdd } = this.state;
    const formValue = this.form.getFieldsValue();
    const currentValue = isAdd ? {} : this.state.record;
    if (!this.validation(formValue)) {
      message.error('请填写完整信息');
      return;
    }
    let newRecord = { ...currentValue, ...formValue };
    newRecord.permission_ids = this.state.selectedRowKeys;
    const self = this;
    if (!isAdd) {
      const editApi = new Api({
        method: 'PUT',
        path: `/roles/${this.state.record.id}`,
        data: newRecord,
        success: () => {
          this.props.onSure();
          self.close();
        },
        error: (msg) => {
          message.error(msg);
        }
      });
      editApi.run();
    } else {
      const addApi = new Api({
        method: 'POST',
        path: '/roles',
        data: newRecord,
        success: (json) => {
          newRecord = { ...json };
          this.props.onSure();
          self.close();
        },
        error: (msg) => {
          message.error(msg);
        }
      });
      addApi.run();
    }
  }
  onSelectChange = (selectedRowKeys) => {
    this.setState({
      selectedRowKeys
    });
  }
  render() {
    const { selectedRowKeys } = this.state;
    const title = this.state.isAdd ? '新增' : '修改';
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange.bind(this),
    };
    const columns = this.generatorColumns();
    return (
      <div>
        <Modal
          title={`${title}角色`}
          visible={this.state.visible}
          onOk={this.handleOk.bind(this)}
          onCancel={() => {
            this.close();
          }}
          confirmLoading={this.state.loading}
          className="add-role-modal middle-modal"
          width={1000}
        >
          <AddForm
            initialValue={this.state.record ? this.state.record : ''}
            ref={(ref) => { this.form = ref; }}
          />
          <div className="table-wrap">
            <Table
              rowKey={record => record.id}
              columns={columns}
              bordered
              dataSource={this.state.data}
              pagination={{
                pageSize: PAGE_SIZE,
                total: this.state.dataCount,
                current: this.state.listPage,
                onChange: this.onListPageChange.bind(this)
              }}
              rowSelection={rowSelection}
            />
          </div>
        </Modal>
      </div>
    );
  }
}

export default AddModal;
